<template>
  <div class="app-container">
    <el-form class="formList"
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
      size="small">
      <el-row>
        <el-form-item label="项目名称"
          prop="name">
          <el-input v-model="queryParams.name"
            placeholder="请输入项目名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            style="width: 232px" />
        </el-form-item>

        <el-form-item label="门店"
          prop="storeId">
          <el-select v-model="queryParams.storeIds"
            placeholder="请选择门店"
            clearable
            multiple
            size="small"
            style="width: 232px"
            @keyup.enter.native="handleQuery">
            <el-option v-for="dict in storeInFoOptions"
              :key="dict.storeId"
              :label="dict.storeName"
              :value="dict.storeUid" />
          </el-select>
        </el-form-item>

        <el-form-item label="渠道来源"
          prop="sourcePlatform">
          <el-select v-model="queryParams.sourcePlatform"
            multiple
            placeholder="请选择渠道来源"
            clearable
            size="small"
            style="width: 232px"
            @keyup.enter.native="handleQuery">
            <el-option v-for="dict in sourcePlatformOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="日期"
          prop="applyAuthTimeArray">
          <el-date-picker v-model="queryParams.applyAuthTimeArray"
            type="daterange"
            align="right"
            style="width: 232px"
            value-format="yyyy-MM-dd"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item style="margin-left: 22px">
          <el-button type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh"
            size="mini"
            @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-row>

    </el-form>

    <!-- <el-row style="height: 70px;" class="row-mbinfo">

            <el-col :span="7" style="padding-left: 400px;">
                <div >
                    <span>{{ listData.number || 0}}</span><br/>
                <span>订单数量</span>

                </div>

            </el-col>

            <el-col :span="7" style="padding-left: 400px;">
                <div >
                <span>{{ listData.amountStr || 0}}</span><br/>
                <span>订单金额</span>
            </div>
            </el-col>

        </el-row> -->
    <div class="order-data-show">
      <div class="order-data-item"
        v-for="(item, index) in countInfoArr"
        :key="index">
        <!-- <div class="order-data-item-img"><img :src="item.img"
            alt="" /></div> -->
        <div class="order-data-item-info">
          <div class="order-data-item-label">{{ item.title }}</div>
          <div class="order-data-item-num"
            :style="{ color: item.color }">
            <span :style="{ color: item.color }"
              class="order-data-item-num">{{ item.unit }}</span>
            {{ listData[item.value] || 0 }}
          </div>
        </div>
      </div>
    </div>

    <el-row class="row-mbinfo">
      <el-col :span="1.5">
        <el-button type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleSave">导出</el-button>
        <el-button type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExportDetail">导出明细</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch"
        @queryTable="getList"></right-toolbar>
    </el-row>
    <div class="divTable">
      <el-table border
        v-loading="loading"
        :data="brandList"
        @selection-change="handleSelectionChange">
        <el-table-column label="项目名称"
          align="center"
          prop="name" />
        <el-table-column label="耗卡数量"
          align="center"
          prop="number" />
        <el-table-column label="耗卡数量占比"
          align="center"
          prop="numberProportionStr" />
        <el-table-column label="耗卡金额"
          align="center"
          prop="amountStr" />
        <el-table-column label="耗卡金额占比"
          align="center"
          prop="amountProportionStr" />
        <el-table-column label="操作"
          align="center"
          prop="createTime">
          <template slot-scope="scope">
            <el-button type="text"
              size="mini"
              icon="el-icon-zoom-in"
              @click="handlee(scope.row)">详情</el-button>
          </template>
        </el-table-column>

      </el-table>

      <pagination v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <el-dialog title="详情"
      :visible.sync="dialogVisible"
      width="70%">
      <el-table border
        :data="list">
        <el-table-column label="用户姓名"
          align="center"
          prop="customerName" />
        <el-table-column label="项目名称"
          align="center"
          prop="serviceName" />
        <el-table-column label="耗卡数量"
          align="center"
          prop="times" />
        <el-table-column label="耗卡面值"
          align="center"
          prop="priceStr" />
        <el-table-column label="日期"
          align="center"
          prop="subscribeDate" />
        <el-table-column label="到店次数"
          align="center"
          prop="storeNumber" />
        <el-table-column label="项目叠加"
          align="center"
          prop="storeItemNumber" />
        <el-table-column label="美容师"
          align="center"
          prop="name" />
        <el-table-column label="卡项来源"
          align="center"
          prop="sourcePlatformStr" />
        <el-table-column label="门店名称"
          align="center"
          prop="storeName" />

      </el-table>

      <pagination v-show="totalQuery > 0"
        :total="totalQuery"
        :page.sync="query.pageNum"
        :limit.sync="query.pageSize"
        @pagination="getListDetail" />

    </el-dialog>

  </div>
</template>

<script>

import {
  selectGroup
} from "@/api/platform/store"


import {
  selectCardConsumptionSale, selectCardConsumptionSaleByProUidAndType
} from "@/api/statistics/statistics";


import { onInput } from "@/utils/util";
export default {
  name: "Brand",
  components: {

  },
  data () {
    return {
      sourcePlatformOptions: [
        {
          "value": "applets",
          "label": "小程序"
        },
        {
          "value": "meituan",
          "label": "美团"
        }, {
          "value": "dithering",
          "label": "抖音"
        }
      ],
      listData: {},
      list: [],
      totalQuery: 0,
      dialogVisible: false,
      query: {
        pageSize: 10,
        pageNum: 1,
        type: '',
        proUid: '',
      },
      selectedDataCopy: [{}],
      selectedData: [],
      storeOpen: false,
      selectedDataStore: {},
      couponOpen: false,
      selectedDataCoupon: {},
      cardAOpen: false,
      selectedDataCard: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //选中数组的名字
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 储值/系列表格数据
      brandList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openA: false,
      // 用于类别关联的分类显示
      dialogVisible: false,
      //常用状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        phone: null,
        startTime: null,
        endTime: null,
        applyAuthTimeArray: [],
        receiveCustomerName: null,
        receiveCustomerPhone: null,
        receiveStatus: null,
        nickName: null,
        name: null,
        storeId: '',
        storeIds: [],
        platSource: '',
        sourcePlatform: [],
      },
      countInfoArr: [
        {
          img: require("@/assets/images/order-icon-14.png"),
          title: "订单数量",
          value: "number",
          color: "#E00065",
          unit: "",
        },
        {
          img: require("@/assets/images/order-icon-11.png"),
          title: "耗卡金额",
          value: "amountStr",
          color: "#FFA082",
          unit: "￥",
        },
      ],
      // 商品
      productOpen: false,
      selectedDataProduct: {},



      options: [
        {
          value: "1",
          label: "已领取",
        },
        {
          value: "0",
          label: "未领取",
        },
      ],
      // 表单参数
      form: {
        customerName: null,
        phone: "",
        dataPriority: "",
        isDataValue: "",
        rightType: "",
      },
      storeInFoOptions: [],
      // 表单校验
      rules: {
        rechargeName: [
          {
            required: true,
            message: "储值名称不能为空",
            trigger: "blur",
          },
        ],
        isDataValue: [
          {
            required: true,
            message: "储值属性不能为空",
            trigger: "change",
          },
        ],
        rightType: [
          {
            required: true,
            message: "储值权益不能为空",
            trigger: "change",
          },
        ],
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  created () {
    this.getList();
    this.getDicts("sys_data_status").then((response) => {
      this.statusOptions = response.data;
    });
    selectGroup().then(response => {
      this.storeInFoOptions = response.data || [];
    });
  },
  watch: {

  },
  methods: {
    onInput,
    handlee (row) {
      this.query.serviceId = row.serviceId;
      this.query.startTime = this.queryParams.startTime;
      this.query.endTime = this.queryParams.endTime;
      this.getListDetail();
    },
    tabResponCard () {
      this.selectedDataCard = {};
    },
    tabResponCoupon () {
      this.selectedDataCoupon = {};
    },
    tabRespon () {
      this.selectedDataStore = {};
    },
    tabResponProduct () {
      this.selectedDataProduct = {};
    },
    dataPriorityInput (value) {
      let js = value + "";
      return js.replace(/^(0+)|[^\d]+/g, "");
    },
    /** 查询储值/系列列表 */

    getListDetail () {
      this.query.storeIds = this.queryParams.storeIds,
        selectCardConsumptionSaleByProUidAndType(this.query).then(response => {
          this.list = response.rows
          this.totalQuery = response.total;
          this.dialogVisible = true;
        })
    },
    getList () {
      if (this.queryParams.applyAuthTimeArray != null && this.queryParams.applyAuthTimeArray.length > 0) {
        let arr = this.queryParams.applyAuthTimeArray;
        this.queryParams.startTime = arr[0] + " 00:00:00";
        this.queryParams.endTime = arr[1] + " 23:59:59";
      } else {
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;
      }
      this.loading = true;
      selectCardConsumptionSale(this.queryParams).then((response) => {
        this.brandList = response.rows;
        this.listData = response.data;
        this.total = response.total;
        this.loading = false;
      });
    },

    p (s) {
      return s < 10 ? "0" + s : s;
    },

    selectCommodityCoupon () {
      this.$forceUpdate();
      this.couponOpen = true;
      console.log(this.couponOpen);
      // this.$nextTick(() => {
      //   this.$refs["selTableCoupon"].greet(this.selectedDataCoupon);
      // });
    },

    //调用子组件中方法，向子组件传值
    selectCommodity () {
      this.$forceUpdate();
      this.openA = true;
      this.$nextTick(() => {
        this.$refs["selTable"].greet(this.selectedData);
      });
    },

    selectCommodityCard () {
      this.$forceUpdate();
      this.cardAOpen = true;
      this.$nextTick(() => {
        this.$refs["selTableCard"].greet(this.selectedDataCard);
      });
    },

    selectCommodityProduct () {
      this.productOpen = true;
      this.$nextTick(() => {
        this.$refs["selTableProduct"].greet(this.selectedDataProduct);
      });
    },

    multipleSelection (data) {
      this.openA = false;
      this.selectedData = data;
      // this.$nextTick(() => {
      //   this.$refs.child.getList();
      // });
    },

    selectCommodityService () {
      this.$forceUpdate();
      this.storeOpen = true;
      // this.$nextTick(() => {
      //   this.$refs["selTable"].greet(this.selectedDataStore);
      // });
    },

    toCloseBoxCoupon () {
      this.couponOpen = false;
    },

    toCloseBoxCard () {
      this.cardAOpen = false;
    },

    toCloseBoxProduct () {
      this.productOpen = false;
    },

    toCloseBoxStore () {
      this.storeOpen = false;
    },

    toCloseBox () {
      this.open = false;
    },

    multipleSelectionCoupon (data) {
      this.couponOpen = false;
      this.selectedDataCoupon = data;
      this.$nextTick(() => {
        this.$refs.childCoupon.getList();
      });
    },

    multipleSelectionStore (data) {
      this.storeOpen = false;
      this.selectedDataStore = data;
      this.$nextTick(() => {
        this.$refs.childStore.getList();
      });
    },

    multipleSelectionCard (data) {
      this.cardAOpen = false;
      this.selectedDataCard = data;
      this.$nextTick(() => {
        this.$refs.childCard.getList();
      });
    },

    multipleSelectionProduct (data) {
      this.productOpen = false;
      this.selectedDataProduct = data;
      this.$nextTick(() => {
        this.$refs.childProduct.getList();
      });
    },

    getSTime (val) {
      //手动赋值，使其通过校验

      const d = new Date(val[0]);
      const resDate =
        d.getFullYear() +
        "-" +
        this.p(d.getMonth() + 1) +
        "-" +
        this.p(d.getDate());
      const resTime =
        this.p(d.getHours()) +
        ":" +
        this.p(d.getMinutes()) +
        ":" +
        this.p(d.getSeconds());
      this.form.startTime = resDate + " " + resTime;
      const c = new Date(val[1]);
      const resDatec =
        c.getFullYear() +
        "-" +
        this.p(c.getMonth() + 1) +
        "-" +
        this.p(c.getDate());
      const resTimec =
        this.p(c.getHours()) +
        ":" +
        this.p(c.getMinutes()) +
        ":" +
        this.p(c.getSeconds());
      this.form.endTime = resDatec + " " + resTimec;
    },

    handleChange (value) {
      console.log(value);
    },

    handleRemove (file, fileList) { },
    handlePictureCardPreviewLogo (file) {
      this.logoUr = file.url;
      this.dialogVisible = true;
    },
    handlePictureCardPreviewImg (file) {
      this.deviceImage = file.url;
      this.dialogVisible = true;
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 关联的取消按钮
    cancelBrand () {
      this.openBrand = false;
      this.reset();
    },
    // 表单重置
    reset () {
      // this.form = {
      //   rechargeName: null,
      //   rechargeIcon: null,
      //   isDataValue: '',
      //   dataPriority: 10,
      //   rightType: ''
      // };
      this.form.rechargeName = null;
      this.form.rechargeIcon = null;
      this.form.isDataValue = "";
      this.form.dataPriority = 10;
      this.form.rightType = "";
      this.resetForm("form");
      if (this.$refs["form"]) {
        this.$refs["form"].resetFields();
      }
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.queryParams.storeIds = [];
      this.handleQuery();
    },
    /** 储值菜单 */
    getMenuTreeselect () {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data;
      });
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.rechargeId);
      this.names = selection.map((item) => item.rechargeName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      //用于禁用删除
      if (this.multiple == false) {
        for (var i = 0; i < selection.length; i++) {
          var element = selection[i];
          if ("1" === element.dataStatus) {
            this.multiple = true;
            break;
          }
        }
      }
    },
    // 状态修改
    handleStatusChange (row) {
      let text = row.dataStatus === "0" ? "无效" : "有效";
      this.$confirm(
        '确定要把储值名称为"' + row.rechargeName + '"设为' + text + "吗？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return updateBrandStatus(row.rechargeId, row.dataStatus);
        })
        .then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        })
        .catch(function () {
          row.dataStatus = row.dataStatus === "0" ? "1" : "0";
        });
    },

    // 状态修改
    handleStatusChangeA (row) {
      let text = row.isRecommend === "0" ? "不推荐" : "推荐";
      this.$confirm(
        '确定要把储值名称为"' + row.rechargeName + '"设为' + text + "吗？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return updateBrandStatusA(row.rechargeId, row.isRecommend);
        })
        .then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        })
        .catch(function () {
          row.isRecommend = row.isRecommend === "0" ? "1" : "0";
        });
    },

    /** 新增按钮操作 */
    handleAdd () {
      this.selectedDataCopy = [{}];
      this.reset();
      this.open = true;
      this.title = "添加储值";
    },
    handleSave () {
      this.download('prod-api/statistics/selectCardConsumptionSaleExport', {
        ...this.queryParams
      }, `门店销售数据.xlsx`)

    },
    handleExportDetail () {
      this.download('prod-api/statistics/selectCardConsumptionSaleDetailExport', {
        ...this.queryParams
      }, `耗卡订单表.xlsx`)
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.$router.push("/service/recharge/editData/" + row.rechargeId);

      // this.reset();
      // const rechargeId = row.rechargeId || this.ids;
      // getBrand(rechargeId).then((response) => {
      //   this.form = response.data;
      //   console.log(this.form);
      //   this.selectedDataCopy[0].rechargeMoney = this.form.rechargeMoney;
      //   this.selectedDataCopy[0].goldCoin = this.form.goldCoin;
      //   this.selectedDataCopy[0].silverCoin = this.form.silverCoin;
      //   this.selectedDataCopy[0].score = this.form.score;
      //   this.form.timeValue = [];
      //   this.form.timeValue.push(this.form.startTime || "");
      //   this.form.timeValue.push(this.form.endTime || "");
      //   this.open = true;
      //   this.title = "修改储值";
      // });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs.childs.selectImgs();
      this.form.rechargeMoney = this.selectedDataCopy[0].rechargeMoney;
      this.form.goldCoin = this.selectedDataCopy[0].goldCoin;
      this.form.silverCoin = this.selectedDataCopy[0].silverCoin;
      this.form.score = this.selectedDataCopy[0].score;

      // 选择权益
      if (this.form.rightType == "coupon") {
        // 获取id this.selectedDataCoupon
        this.form.rightObjectId = this.selectedDataCoupon.couponUid;
        if (this.form.rightObjectId == null) {
          this.msgError("请选择优惠券数据");
          return;
        }
      } else if (this.form.rightType == "card") {
        // 获取id  this.selectedDataCard
        this.form.rightObjectId = this.selectedDataCard.cardId;
        if (this.form.rightObjectId == null) {
          this.msgError("请选择套餐卡数据");
          return;
        }
      } else if (this.form.rightType == "service") {
        // 获取id  this.selectedDataStore
        this.form.rightObjectId = this.selectedDataStore.itemId;
        if (this.form.rightObjectId == null) {
          this.msgError("请选择服务项目数据");
          return;
        }
      } else if (this.form.rightType == "product") {
        // 获取id  this.selectedDataProduct
        this.form.rightObjectId = this.selectedDataProduct.productUid;
        if (this.form.rightObjectId == null) {
          this.msgError("请选择商品数据");
          return;
        }
      }

      //console.log(this.form);
      return
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.rechargeId != null) {
            updateBrand(this.form).then((response) => {
              // updateRight(this.form)
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.selectedDataCard = {};
              this.selectedDataCoupon = {};
              this.selectedDataStore = {};
              this.selectedDataProduct = {};
            });
          } else {
            addBrand(this.form).then((response) => {
              // form.rightObjectId=
              // addRight(this.form)
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.selectedDataCard = {};
              this.selectedDataCoupon = {};
              this.selectedDataStore = {};
              this.selectedDataProduct = {};
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const deviceIds = row.rechargeId || this.ids;
      const names = row.rechargeName || this.names;
      this.$confirm('是否确认删除储值名称为"' + names + '"的储值?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delBrand(deviceIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => { });
    },

    /** 导出按钮操作 */
    handleExport () {
      this.download(
        "device/brand/export",
        {
          ...this.queryParams,
        },
        `商品储值.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.treeOne {
  display: inline-block;
  margin-right: 200px;
}

.treeTwo {
  display: inline-block;
}

.image-rows {
  width: 80px;
  height: auto;
}

.order-data-show {
  display: flex;
  margin: 10px 0;
  .order-data-item {
    flex: 1;
    padding: 16px 32px;
    display: flex;
    align-items: center;
    background-color: #fff;
    border-radius: 8px;
    &:not(:last-child) {
      margin-right: 12px;
    }
    .order-data-item-img {
      width: 68px;
      height: 68px;
      margin-right: 32px;
    }
    .order-data-item-num {
      font-size: 30px;
      color: #5da9ef;
      font-weight: 500;
      line-height: 1;
      display: flex;
      align-items: flex-end;
      .order-data-item-num-unit {
        font-size: 16px;
        margin-left: 12px;
        line-height: 1.4;
      }
    }
    .order-data-item-label {
      font-size: 16px;
      color: #999;
      line-height: 1;
      margin-bottom: 14px;
    }
  }
}
</style>
